package com.ruoyi.hxy.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.gson.Gson;
import com.ruoyi.hxy.constant.HxyConstant;
import com.ruoyi.hxy.dto.order.*;
import com.ruoyi.hxy.dto.order.wait.HxyWaitOrderDataResDto;
import com.ruoyi.hxy.dto.order.wait.HxyWaitOrderResultResDto;
import com.ruoyi.hxy.service.IHxyOrderService;
import com.ruoyi.xp.order.dto.*;
import com.ruoyi.xp.order.service.IOrderInfoService;
import com.ruoyi.xp.order.service.IOrderService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chendx
 */
@Service
public class HxyOrderServiceImpl implements IHxyOrderService {

    private static final Logger log = LoggerFactory.getLogger(HxyOrderServiceImpl.class);

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderInfoService orderInfoService;

    @Override
    public OrderItemInfoDto getOrderItemByOrderSn(String orderSn) throws IOException {

        log.info("开始同步货效小易订单明细信息:{}", orderSn);

        OrderItemInfoDto orderItemInfoDto = new OrderItemInfoDto();

        //请求货小易订单查询接口
        HxyOrderResultResDto hxyOrderResultResDto = getHxyOrderItemByOrderSn(orderSn);
        //请求货小易代处理订单查询接口
        HxyWaitOrderResultResDto hxyWaitOrderResultResDto = getHxyWaitOrderItemByOrderSn(orderSn);

        //判断接口是否请求成功
        if (HxyConstant.ORDER_RESULT_SUCCESS.equals(hxyOrderResultResDto.getResult()) || HxyConstant.ORDER_RESULT_SUCCESS.equals(hxyWaitOrderResultResDto.getResult())) {

            //获取货小易返回数据内容
            HxyOrderDataResDto hxyOrderDataResDto = hxyOrderResultResDto.getHxyOrderDataResDto();
            HxyWaitOrderDataResDto hxyWaitOrderDataResDto = hxyWaitOrderResultResDto.getHxyWaitOrderDataResDto();
            //货小易订单商品对象
            List<? extends HxyOrderItemResDto> hxyOrderItemResDtoList;
            String warehouseOrderStatus = null;
            String warehouseProcessStatus = null;

            //判断订单查询返回的数据报文是否为空，并且取出第一个订单的商品信息
            if (ObjectUtil.isNotNull(hxyOrderDataResDto) && ObjectUtil.isNotNull(hxyOrderDataResDto.getHxyOrderResDtoList()) &&
                    CollectionUtil.isNotEmpty(hxyOrderDataResDto.getHxyOrderResDtoList()) && CollectionUtil.isNotEmpty(hxyOrderDataResDto.getHxyOrderResDtoList().get(0).getHxyOrderItemResDtoList())) {
                //取出第一个订单的商品信息
                hxyOrderItemResDtoList = hxyOrderDataResDto.getHxyOrderResDtoList().get(0).getHxyOrderItemResDtoList();
                warehouseOrderStatus = hxyOrderDataResDto.getHxyOrderResDtoList().get(0).getOrderStatus();
                warehouseProcessStatus = hxyOrderDataResDto.getHxyOrderResDtoList().get(0).getProcessStatus();
            } //判断待处理订单查询返回的数据报文是否为空，并且取出第一个订单的商品信息
            else if (ObjectUtil.isNotNull(hxyWaitOrderDataResDto) && ObjectUtil.isNotNull(hxyWaitOrderDataResDto.getHxyWaitOrderResDtoList()) &&
                    ArrayUtil.isNotEmpty(hxyWaitOrderDataResDto.getHxyWaitOrderResDtoList()) &&
                    ArrayUtil.isNotEmpty(hxyWaitOrderDataResDto.getHxyWaitOrderResDtoList().get(0).getHxyWaitOrderPackageResDtoList().get(0).getHxyWaitOrderItemResDtoList())) {
                //取出第一个订单的商品信息
                hxyOrderItemResDtoList = hxyWaitOrderDataResDto.getHxyWaitOrderResDtoList().get(0).getHxyWaitOrderPackageResDtoList().get(0).getHxyWaitOrderItemResDtoList();
                warehouseOrderStatus = hxyWaitOrderDataResDto.getHxyWaitOrderResDtoList().get(0).getAppOrderStatus();
            }else {
                log.info("无订单商品信息:{}, {}", orderSn, hxyOrderResultResDto.getResult());
                return orderItemInfoDto;
            }

            //将商品内容转换成将要存储的商品字段
            orderItemInfoDto.setOrderSn(orderSn);
            orderItemInfoDto.setWarehouseOrderStatus(warehouseOrderStatus);
            orderItemInfoDto.setWarehouseProcessStatus(warehouseProcessStatus);
            orderItemInfoDto.setOrderItemDtoList(getOrderItem(hxyOrderItemResDtoList, orderSn));
        } else {
            log.info("同步货效小易订单明细信息失败:{}, {}", orderSn, hxyOrderResultResDto.getResult());
        }

        log.info("结束同步货效小易订单明细信息:{}", orderSn);

        return orderItemInfoDto;
    }

    @Override
    public BigDecimal getOrderWarehousePackageAmount(String orderSn) throws IOException {

        log.info("开始同步货效小易订单明细信息:{}", orderSn);

        //请求货小易订单查询接口
        HxyOrderResultResDto hxyOrderResultResDto = getHxyOrderItemByOrderSn(orderSn);
        BigDecimal warehousePackageAmount = new BigDecimal(0);
        if (HxyConstant.ORDER_RESULT_SUCCESS.equals(hxyOrderResultResDto.getResult())) {
            HxyOrderDataResDto hxyOrderDataResDto = hxyOrderResultResDto.getHxyOrderDataResDto();
            if (ObjectUtil.isNotNull(hxyOrderDataResDto) && ObjectUtil.isNotNull(hxyOrderDataResDto.getHxyOrderResDtoList()) &&
                    CollectionUtil.isNotEmpty(hxyOrderDataResDto.getHxyOrderResDtoList()) && CollectionUtils.isNotEmpty(hxyOrderDataResDto.getHxyOrderResDtoList().get(0).getHxyOrderTailPackageCostFeeResDtoList())) {
                List<HxyOrderTailPackageCostFeeResDto> hxyOrderTailPackageCostFeeResDtoList = hxyOrderDataResDto.getHxyOrderResDtoList().get(0).getHxyOrderTailPackageCostFeeResDtoList();
                for (HxyOrderTailPackageCostFeeResDto hxyOrderTailPackageCostFeeResDto : hxyOrderTailPackageCostFeeResDtoList) {
                    warehousePackageAmount = warehousePackageAmount.add(hxyOrderTailPackageCostFeeResDto.getFee());
                }
            }

        }
        log.info("结束同步货效小易订单明细信息:{}", orderSn);

        return warehousePackageAmount;
    }


    /**
     * 获取商品明细信息
     *
     * @param hxyOrderItemResDtoList
     * @param orderSn
     * @return
     */
    private List<OrderItemDto> getOrderItem(List<? extends HxyOrderItemResDto> hxyOrderItemResDtoList, String orderSn) {
        //获取订单的商品信息
        List<OrderItemDto> orderItemDtoList = new ArrayList<>();
        if (ObjectUtil.isNotNull(hxyOrderItemResDtoList)) {
            for (HxyOrderItemResDto hxyOrderItemResDto : hxyOrderItemResDtoList) {
                OrderItemDto orderItemDto = new OrderItemDto();
                orderItemDto.setOrderSn(orderSn);
                orderItemDto.setItemId(hxyOrderItemResDto.getPlatformItemId());
                orderItemDto.setItemName(hxyOrderItemResDto.getTitle());
                orderItemDto.setSellerItemId(hxyOrderItemResDto.getPlatformItemNum());
                orderItemDto.setModelId(hxyOrderItemResDto.getPlatformSkuId());
                orderItemDto.setModelName(hxyOrderItemResDto.getSkuSubName());
                orderItemDto.setSellerModelId(hxyOrderItemResDto.getPlatformOuterSkuId());
                orderItemDto.setModelQuantityPurchased(hxyOrderItemResDto.getQuantity());
                orderItemDto.setModelOriginalPrice(hxyOrderItemResDto.getOriginalPrice());
                orderItemDto.setModelDiscountedPrice(hxyOrderItemResDto.getDiscountedPrice());
                orderItemDto.setWeight(new BigDecimal(hxyOrderItemResDto.getWeight() == null ? 0 : hxyOrderItemResDto.getWeight()));
                orderItemDtoList.add(orderItemDto);

                if (ObjectUtil.isNotNull(hxyOrderItemResDto.getHxyOrderItemGoodsSkuResDtoList())) {
                    List<OrderItemGoodsDto> orderItemGoodsDtoList = getOrderItemGoods(hxyOrderItemResDto.getHxyOrderItemGoodsSkuResDtoList(), orderSn, hxyOrderItemResDto.getPlatformSkuId());
                    orderItemDto.setOrderItemGoodsDtoList(orderItemGoodsDtoList);
                }

                if (ObjectUtil.isNotNull(hxyOrderItemResDto.getHxyOrderItemHeadPackageResDtoList())) {
                    List<OrderItemHeadPackageDto> orderItemHeadPackageDtoList = getOrderItemHeadPackages(hxyOrderItemResDto.getHxyOrderItemHeadPackageResDtoList(), orderSn, hxyOrderItemResDto.getPlatformSkuId());
                    orderItemDto.setOrderItemHeadPackageDtoList(orderItemHeadPackageDtoList);
                }
            }
        }
        return orderItemDtoList;
    }

    /**
     * 获取仓库的商品信息
     *
     * @param hxyOrderItemGoodsSkuResDtoList
     * @param orderSn
     * @return
     */
    private List<OrderItemGoodsDto> getOrderItemGoods(List<? extends HxyOrderItemGoodsSkuResDto> hxyOrderItemGoodsSkuResDtoList, String orderSn, Long modelId) {
        //获取订单明细仓库货物信息
        List<OrderItemGoodsDto> orderItemGoodsDtoList = new ArrayList<>();
        if (ObjectUtil.isNotNull(hxyOrderItemGoodsSkuResDtoList)) {
            for (HxyOrderItemGoodsSkuResDto hxyOrderItemGoodsSkuResDto : hxyOrderItemGoodsSkuResDtoList) {
                OrderItemGoodsDto orderItemGoodsDto = new OrderItemGoodsDto();
                orderItemGoodsDto.setOrderSn(orderSn);
                orderItemGoodsDto.setWarehouseId(hxyOrderItemGoodsSkuResDto.getWarehouseId());
                orderItemGoodsDto.setGoodsClass(hxyOrderItemGoodsSkuResDto.getGoodsClass());
                orderItemGoodsDto.setGoodsName(hxyOrderItemGoodsSkuResDto.getGoodsName());
                orderItemGoodsDto.setGoodsSkuSubName(hxyOrderItemGoodsSkuResDto.getGoodsSkuSubName());
                orderItemGoodsDto.setModelId(modelId);
                orderItemGoodsDto.setGoodsId(hxyOrderItemGoodsSkuResDto.getGoodsSkuId());
                orderItemGoodsDto.setQuantity(hxyOrderItemGoodsSkuResDto.getQuantity());
                orderItemGoodsDto.setLogoOssPath(hxyOrderItemGoodsSkuResDto.getLogoOssPath());
                orderItemGoodsDto.setLogoUrl(hxyOrderItemGoodsSkuResDto.getLogoUrl());
                orderItemGoodsDtoList.add(orderItemGoodsDto);
            }
        }
        return orderItemGoodsDtoList;
    }

    /**
     * 获取采购的商品信息
     *
     * @param hxyOrderItemHeadPackageResDtoList
     * @param orderSn
     * @return
     */
    private List<OrderItemHeadPackageDto> getOrderItemHeadPackages(List<? extends HxyOrderItemHeadPackageResDto> hxyOrderItemHeadPackageResDtoList, String orderSn, Long modelId) {
        //获取订单明细外部采购货物信息对象
        List<OrderItemHeadPackageDto> orderItemHeadPackageDtoList = new ArrayList<>();
        if (ObjectUtil.isNotNull(hxyOrderItemHeadPackageResDtoList)) {
            for (HxyOrderItemHeadPackageResDto hxyOrderItemHeadPackageResDto : hxyOrderItemHeadPackageResDtoList) {
                OrderItemHeadPackageDto orderItemHeadPackageDto = new OrderItemHeadPackageDto();
                orderItemHeadPackageDto.setOrderSn(orderSn);
                orderItemHeadPackageDto.setWarehouseId(hxyOrderItemHeadPackageResDto.getWarehouseId());
                orderItemHeadPackageDto.setModelId(modelId);
                orderItemHeadPackageDto.setLogisticsCompany(hxyOrderItemHeadPackageResDto.getLogisticsCompany());
                orderItemHeadPackageDto.setTrackingNo(hxyOrderItemHeadPackageResDto.getTrackingNo());
                orderItemHeadPackageDto.setPurchasePlatform(hxyOrderItemHeadPackageResDto.getPurchasePlatform());
                orderItemHeadPackageDto.setPurchasePlatformName(hxyOrderItemHeadPackageResDto.getPurchasePlatformName());
                orderItemHeadPackageDto.setPurchaseOrderSn(hxyOrderItemHeadPackageResDto.getPurchaseOrderSn());
                orderItemHeadPackageDto.setPurchaseOrderDetailUrl(hxyOrderItemHeadPackageResDto.getPurchaseOrderDetailUrl());
                orderItemHeadPackageDto.setAccountNote(hxyOrderItemHeadPackageResDto.getAccountNote());
                orderItemHeadPackageDto.setIsApplyReturn(hxyOrderItemHeadPackageResDto.getIsApplyReturn());
                orderItemHeadPackageDto.setReturnStatus(hxyOrderItemHeadPackageResDto.getReturnStatus());
                orderItemHeadPackageDto.setSignStatus(hxyOrderItemHeadPackageResDto.getSignStatus());
                orderItemHeadPackageDto.setPackStatus(hxyOrderItemHeadPackageResDto.getPackStatus());
                orderItemHeadPackageDto.setWeight(hxyOrderItemHeadPackageResDto.getWeight());
                orderItemHeadPackageDto.setPackageType(hxyOrderItemHeadPackageResDto.getPackageType());
                orderItemHeadPackageDto.setHasSendPackageUnsign(hxyOrderItemHeadPackageResDto.getHasSendPackageUnsign());
                orderItemHeadPackageDto.setArriveWarehouseTime(hxyOrderItemHeadPackageResDto.getGmtArriveWarehouse());
                orderItemHeadPackageDto.setSignTime(hxyOrderItemHeadPackageResDto.getGmtSign());
                orderItemHeadPackageDto.setRefuseTime(hxyOrderItemHeadPackageResDto.getGmtRefuse());
                orderItemHeadPackageDto.setReturnTime(hxyOrderItemHeadPackageResDto.getGmtAgreeReturn());
                orderItemHeadPackageDto.setAgreeReturnTime(hxyOrderItemHeadPackageResDto.getGmtAgreeReturn());
                orderItemHeadPackageDto.setPrintReturnInfoTime(hxyOrderItemHeadPackageResDto.getGmtPrintReturnInfo());
                orderItemHeadPackageDto.setApplyReturnTime(hxyOrderItemHeadPackageResDto.getGmtApplyReturn());
                orderItemHeadPackageDto.setPackTime(hxyOrderItemHeadPackageResDto.getGmtPack());
                orderItemHeadPackageDto.setQuantity(hxyOrderItemHeadPackageResDto.getQuantity());
                orderItemHeadPackageDto.setLogoUrl(hxyOrderItemHeadPackageResDto.getLogoUrl());
                orderItemHeadPackageDtoList.add(orderItemHeadPackageDto);
            }
        }
        return orderItemHeadPackageDtoList;
    }


    private HxyOrderResultResDto getHxyOrderItemByOrderSn(String orderSn) throws IOException{
        HttpClient httpClient = new DefaultHttpClient();
        String url = "https://kuaigongyuncang.huoxiaoyi.com/api/customer/order/searchOrderList?isManualPlatformOrder=&shopIds=&platformOrderSn=" + orderSn + "&headPackageSignStatus=&trackingNo=&returnStatus=&sortType=desc&platformItemId=&platformSkuId=&gmtOrderStartFrom=&gmtOrderStartTo=&isPartPack=&skuSubName=&hasShopeeFirstMile=&purchasePlatform=&purchaseOrderBuyer=&purchaseOrderStatus=&purchaseOrderSn=&headPackageTrackingNo=&orderTrackingNo=&page=1&pageSize=20&platform=shopee&remaindDeliveryDays=&daysToCancel=&tab=&sortField=gmt_last_delivery&gmtSubmitFrom=&gmtSubmitTo=&searchId=&clearOrderStatus=true";
        HttpGet httpGet = new HttpGet(url);

        httpGet.addHeader("cookie", "_bl_uid=5Rlen8e14y1nnvdmhxswxz3ma5s5; tms_customer=e04k5b9j1dp1vhb9rvrs223q06; customerId=18972; accountType=platform; customerId=18972");
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String responseStr = EntityUtils.toString(entity, "UTF-8");
        HxyOrderResultResDto hxyOrderResultResDto = new Gson().fromJson(responseStr, HxyOrderResultResDto.class);

        System.out.println(hxyOrderResultResDto.getResult());
        return hxyOrderResultResDto;
    }

    private HxyWaitOrderResultResDto getHxyWaitOrderItemByOrderSn(String orderSn) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        String url = "https://kuaigongyuncang.huoxiaoyi.com/api/customer/platform/order/searchWaitSubmitOrderList?platform=shopee&isManualPlatformOrder=&site=&shopIds=&platformOrderSn="+ orderSn +"&isCb=&remaindDeliveryDays=&daysToCancel=&platformItemId=&platformSkuId=&hasHeadPackage=&sortField=gmt_last_delivery&sortType=desc&gmtOrderStartFrom=&gmtOrderStartTo=&applyTrackingNoStatus=&skuSubName=&hasShopeeFirstMile=&purchasePlatform=&purchaseOrderBuyer=&purchaseOrderStatus=&purchaseOrderSn=&headPackageTrackingNo=&orderTrackingNo=&searchId=1671468436768&clearOrderStatus=true&page=1&pageSize=20";
        HttpGet httpGet = new HttpGet(url);

        httpGet.addHeader("cookie", "_bl_uid=5Rlen8e14y1nnvdmhxswxz3ma5s5; tms_customer=e04k5b9j1dp1vhb9rvrs223q06; customerId=18972; accountType=platform; customerId=18972");
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String responseStr = EntityUtils.toString(entity, "UTF-8");
        HxyWaitOrderResultResDto hxyWaitOrderResultResDto = new Gson().fromJson(responseStr, HxyWaitOrderResultResDto.class);

        System.out.println(hxyWaitOrderResultResDto.getResult());
        return hxyWaitOrderResultResDto;
    }

    public static void main(String[] args) throws IOException {
        HxyOrderServiceImpl hxyOrderService = new HxyOrderServiceImpl();
        OrderItemInfoDto orderItemInfoDto = hxyOrderService.getOrderItemByOrderSn("230102AF0GX5WH");
        //HxyWaitOrderResultResDto hxyWaitOrderResultResDto = hxyOrderService.getHxyWaitOrderItemByOrderSn("2212194M9AT8GB");
        System.out.println("1");
    }
}
